package org.dong.samples.dao.Impl;

import java.util.ArrayList;
import java.util.List;
import org.dong.samples.dao.UserSubjectHibernateDAO;
import org.dong.samples.model.PagerModel;
import org.dong.samples.model.Subject;
import org.dong.samples.model.SystemContext;
import org.dong.samples.model.User;
import org.dong.samples.model.UserSubject;
import org.dong.samples.model.vo.SubjectVO;
import org.dong.samples.model.vo.UserVO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.DoubleType;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class UserSubjectHibernateDAOImple extends BaseHibernateDAO<UserSubject> implements UserSubjectHibernateDAO {

	
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession(){
		return this.sessionFactory.getCurrentSession();
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAllUser() throws Exception {
		Session session = getSession();
		String hql = "FROM User";
		List<User> user = session.createQuery(hql).list();
		return user;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Subject> findAllSubject() throws Exception {
		Session session = getSession();
		String hql = "FROM Subject";
		List<Subject> subject = session.createQuery(hql).list();
		return subject;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<UserSubject> findAllUserSubject(){
		Session session = getSession();
		String hql = "FROM UserSubject";
		List<UserSubject> userList = session.createQuery(hql).list();
		return userList;
	}

	@Override
	public User getUserById(String userId) throws Exception {
		Session session = getSession();
		return (User) session.get(User.class, userId);
	}

	@Override
	public Subject getSubjectById(Integer subId) throws Exception {
		Session session = getSession();
		return (Subject) session.get(Subject.class, subId);
	}

	@Override
	public void createUser(User user) throws Exception {
		Session session = getSession();
		session.save(user);
	}

	@Override
	public void editUser(User user) throws Exception {
		Session session = getSession();
		session.update(user);
	}

	@Override
	public void deleteUser(String id) throws Exception {
		Session session = getSession();
		User user = (User) session.get(User.class, id);
		if(user != null){
			session.delete(user);
		}
	}

	@Override
	public void createSubject(Subject subject) throws Exception {
		Session session = getSession();
		session.save(subject);
	}

	@Override
	public void editSubject(Subject subject) throws Exception {
		Session session = getSession();
		session.update(subject);
	}

	@Override
	public void deleteSubject(Integer subId) throws Exception {
		Session session = getSession();
		Subject subject = (Subject) session.get(Subject.class, subId);
		if(subject != null){
			session.delete(subject);
		}
	}


	@SuppressWarnings("unchecked")
	@Override
	public PagerModel<UserVO> pageFindUser() throws Exception {
		Session session = getSession();
		PagerModel<UserVO> page = new PagerModel<UserVO>();
		List<UserVO> list = new ArrayList<UserVO>();
		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getPageSize();
		//分页
		List<User> userList = session.createQuery("FROM User").setFirstResult(offset).setMaxResults(pageSize).list();
		for(User user:userList){
			UserVO vo = new UserVO();
			BeanUtils.copyProperties(user, vo);
			list.add(vo);
		}
		page.setDates(list);
		page.setOffset(offset);
		page.setPageSize(pageSize);
		long totalSize = (long)this.getSession().createQuery("select count(*) from User").uniqueResult();
		page.setTotalSize(totalSize);
		return page;
	}


	@SuppressWarnings("unchecked")
	@Override
	public PagerModel<SubjectVO> pageFindSubject() throws Exception {
		Session session = getSession();
		PagerModel<SubjectVO> page = new PagerModel<SubjectVO>();
		List<SubjectVO> list = new ArrayList<SubjectVO>();
		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getPageSize();
		//分页
			List<Subject> subList = session.createQuery("FROM Subject").setFirstResult(offset).setMaxResults(pageSize).list();
			for(Subject subject:subList){
				SubjectVO vo = new SubjectVO();
				BeanUtils.copyProperties(subject, vo);
				list.add(vo);
			}
			page.setDates(list);
			page.setOffset(offset);
			page.setPageSize(pageSize);
			long totalSize = (long)this.getSession().createQuery("select count(*) from Subject").uniqueResult();
			page.setTotalSize(totalSize);
		return page;
	}
	
	@Override
	public void insertTime(String time, String userId) {
		Session session = getSession();
		String hql = "update exam_user set last_lock_time='"+time+"' where user_id='"+userId+"'";
		session.createSQLQuery(hql).executeUpdate();
		
	}

	@Override
	public void insertCount(Integer count, String userId) {
		Session session = getSession();
		String hql = "update exam_user set login_fail_count='"+count+"' where user_id='"+userId+"'";
		session.createSQLQuery(hql).executeUpdate();
	}


	@Override
	public void editStatus(Integer subId, Integer status) {
		Session session = getSession();
		String hql = "update exam_subject set status='"+status+"' where sub_id='"+subId+"'";
		session.createSQLQuery(hql).executeUpdate();
	}


	
	@SuppressWarnings("unchecked")
	@Override
	public List<Subject> findSubjectByUserId(String userId) {
		List<Subject> SubjectList = new ArrayList<Subject>();
		String hql = " SELECT es.sub_id as subId,es.name as subName,es.description as description,es.test_count as testCount,es.total_time as totalTime,es.total_score as totalScore,es.status as status FROM exam_user_subject eus, exam_subject es WHERE eus.sub_id=es.sub_id AND eus.user_id=:userId ";
		SubjectList = getSession().createSQLQuery(hql)
				.addScalar("subId",IntegerType.INSTANCE)
				.addScalar("subName", StringType.INSTANCE)
				.addScalar("description", StringType.INSTANCE)
				.addScalar("testCount", IntegerType.INSTANCE)
				.addScalar("totalTime", IntegerType.INSTANCE)
				.addScalar("totalScore", DoubleType.INSTANCE)
				.addScalar("status", IntegerType.INSTANCE)
				.setResultTransformer(Transformers.aliasToBean(Subject.class))
				.setString("userId", userId).list();
		return SubjectList;
	}
}
